<?php
/**
 * 微信公众平台临时素材接口测试类
 */
namespace Home\Controller;
use Think\Controller;
use Think\Upload;
use Think\Image;
use Com\Wechat;
use Com\WechatAuth;
use Com\ThumbHandler;

header("Content-type:text/html;chartset=utf-8");   
class MediaController extends Controller{
	private $appid = 'wxb70359eb19266f10';
    private $appsecret = 'd05e862df76a7401e0b2af0f06e8eade';
    private $WechatAuth = '';
    private $access_token = '';


    public function __construct(){
        parent::__construct();
        if(!session('token')){
            $this->WechatAuth = new WechatAuth($this->appid, $this->appsecret); //初始化WechatAuth类
            $WechatAuth = $this->WechatAuth;
            $token = $WechatAuth->getAccessToken(); //获取access_token数组
            session(array('expire'=>$token['expire_in'])); //设置缓存时间
            session('token', $token['access_token']); //缓存token
            $this->access_token = $token['access_token'];
        }else{
            $token = session('token');
            $this->WechatAuth = new WechatAuth($this->appid, $this->appsecret, $token);
            $this->access_token = $token;
        }
        
    }

	public function index(){
		echo 123;
	}

	public function uploadImage(){
		// $separator = DIRECTORY_SEPARATOR;
		// $imgpath = $separator.'public'.$separator.'images'.$separator.'haibao2.jpg';
		// $imgpath = FILE_ROOT.$imgpath;
		// $path = "D:\\\\phpStudy\WWW\wechat\public\images\haibao2.jpg";
		// dump($path);
		// $imgpath = $this->replace_separator($path);
		// dump($imgpath);
		// $img = "D:\phpStudy\WWW\wechat\Public\images\haibao2.jpg";
		// $data = $this->WechatAuth->mediaUpload($img, 'image');
		// dump($data);

		
		$imgpath = './Public/images/haibao2.jpg';
		$dstpath = 'Public/images/new_haibao2.jpg';
				$t = new ThumbHandler(); // 实例化图像处理类
				$t->setSrcImg($imgpath);
				$t->setDstImg($dstpath);

				// 指定缩放比例
				$t->createImg(100,120);

		$srcpath = __ROOT__.$imgpath;
		$newpath = __ROOT__.'/'.$dstpath;
		$this->assign('srcpath',$srcpath);
		$this->assign('newpath',$newpath);
		$this->display();

		// ["type"] => string(5) "image"
	 //    ["media_id"] => string(64) "24rzUk29EcMjbK1mA15IRgmu4WvTSwY4bfWvL4Rxlt_LQueNvv2Mwq86NIlJQ06A"
	 //    ["created_at"] => int(1461120207)
	}

	// windows系统和linux/Unix系统下的路径分隔符不一样，Windows下为”\”，Linux/Unix下则是”/” ，在php中，我们需要处理这种差异。
	// ”\\”统一替换为”/”，当然也可以替换为”\”，再把”/”替换为系统的目录分隔符。
	// 替换文件路径中的分隔符为系统分隔符
	function replace_separator($path){
		while(stripos($path, '//')){
		$path=str_replace('//', '/', $path);
		}
		while(stripos($path, '\\\\')){
		$path=str_replace('\\\\', '/', $path);
		}
		$path=str_replace('/', DIRECTORY_SEPARATOR, $path);
		return $path;
	}

	public function upload(){
		if(IS_POST){
			if(empty($_FILES)){
				$this->error('必须选择上传文件');
			}else{
				$upload = new Upload();
				$upload->maxSize = 3145728; // 设置附件上传大小
				$upload->rootPath = 'Public/'; // 文件上传保存的根路径
				$upload->savePath = 'Uploads/'; // 文件上传的保存路径（相对于根路径）
				$upload->saveName = array('uniqid',''); // 上传文件的保存规则
				$upload->replace = true; // 存在同名文件是否是覆盖
				$upload->exts = array('jpg', 'gif', 'png', 'jpeg'); // 允许上传的文件后缀（留空为不限制）
				$upload->mimes = array('image/png','image/jpg','image/jpeg','image/gif'); // 允许上传的文件类型（留空为不限制）
				$upload->subName = array('date','Ymd'); // 子目录创建方式
				// 上传文件 
				$info = $upload->upload();
				if(!$info){
					$this->error($upload->getError());
				}else{
					// dump($info);
					// foreach($info as $file){
					// 	echo $file['savepath'].$file['savename'];
					// }
					// echo $imginfo = $info[0]['savepath'].$info[0]['savename'];

					$files = array();
					foreach ($info as $file) {
						$files[] = './Public/'.$file['savepath'].$file['savename'];
					}
				}
				// dump($files);
				$image = new Image();
				$updir = './Public/Uploads/'.date('Ymd',NOW_TIME).'/';
				foreach ($files as $key => $img) {
					$image->open($img);
					$image->thumb(640, 640)->save($updir.'thumb_'.$key.'.jpg');
					$image->thumb(320, 320)->save($updir.'m_'.$key.'.jpg');
				}
				dump($updir);
				// $imgsrc = './Public/'.$imginfo;
				// // dump($imgsrc);
				// $image = new Image();
				// $image->open($imgsrc);
				// $image->thumb(150, 150)->save('./thumb.jpg');
				
			}
			
		}else{
			$this->display();
		}
	}

	public function receiveImg(){
		if(IS_POST){
			$data = substr($_POST['formFile'],23);
			$img=base64_decode($data);
			// dump($data);
			dump($img);
		}
	}

	public function test(){
		echo FILE_ROOT;
		dump(__ROOT__);
		dump(__PUBLIC__);
		dump(IS_WIN);
		dump(__APP__);
		dump(dirname(_PHP_FILE_));
		dump(__MODULE__);
		dump(MODULE_NAME);
		dump(MODULE_PATHINFO_DEPR);
		dump(CONTROLLER_NAME);
		dump(APP_PATH);
		dump($_SERVER['SCRIPT_FILENAME']);
		dump(dirname($_SERVER['SCRIPT_FILENAME']));
		dump(__DIR__);
	}
	
}